package com.ycg.vue.context;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description ThreadLocal 实现用户上下文传递
 * @Author jink
 * @Date 2024/1/19
 */
public class ThreadLocalContext {

    public static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<>();

    public static void set(Map<String, Object> map) {
        threadLocal.set(map);
    }

    public static void setUserId(String userId) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) map = new ConcurrentHashMap<>();
        map.put("userId", userId);
        threadLocal.set(map);
    }

    public static void setIp(String ip) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) map = new ConcurrentHashMap<>();
        map.put("ip", ip);
        threadLocal.set(map);
    }

    public static void setUserName(String username) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) map = new ConcurrentHashMap<>();
        map.put("username", username);
        threadLocal.set(map);
    }

    public static String getUserId() {
        if (threadLocal.get() == null) return null;
        return threadLocal.get().get("userId") == null ? null : (String) threadLocal.get().get("userId");
    }

    public static String getIp() {
        if (threadLocal.get() == null) return null;
        return threadLocal.get().get("ip") == null ? null : (String) threadLocal.get().get("ip");
    }

    public static String getUserName() {
        if (threadLocal.get() == null) return null;
        return threadLocal.get().get("username") == null ? null : (String) threadLocal.get().get("username");
    }

    public static void removeUser() {
        threadLocal.remove();
    }
}
